<?php
namespace Home\Controller;

use Think\Controller;

class ThumbController extends Controller {
	
	private $sizes = null;
	
	public function _initialize() {
		$this->sizes = C("THUMB_SIZES");
	}
	
	// 生成预加载缩略图
	public function thumbAction() {
		$isWrite = false;
		if(!IS_SAE){
			return false;
		}
		Header( "Content-type: image/jpeg"); //2.JPEG格式
		$size = I('size', $this->sizes[0]);
		$path = I('path', '', 'urldecode');
		if(!in_array($path, $this->sizes)) $size = $this->sizes[0];
		list($maxWidth, $maxHeight) = explode('x', $size);
		$path = $this->getLocalPic($path);
		$s = new \SaeStorage();
		$arr = explode('/', ltrim($path, './'));
		$domain = array_shift($arr);
		$source = implode('/', $arr);
		$source_url = $s->getUrl($domain, $source);
		if (!$s->fileExists($domain, $source)){
			return false;
		}
		$thumbFilePath = $arr;
		$thumbFileName = array_pop($thumbFilePath);
		$thumbFilePath[] = preg_replace('/(\.\w+)$/', "({$maxWidth}x{$maxHeight})$1", $thumbFileName);
		$thumbFilePath = implode('/', $thumbFilePath);
		$s->delete($domain, $thumbFilePath);
		if($s->fileExists($domain, $thumbFilePath)){
			$thumb_source_url = $s->getUrl($domain, $thumbFilePath);
			$temp_img = imagecreatefromjpeg($thumb_source_url);
		}else{
			$info = getimagesize($source_url);
			$width = $info[0];//获取图片宽度
			$height = $info[1];//获取图片高度
			$r = min($maxHeight/$height, $maxWidth/$width);
			if($r >= 1) {
				$maxHeight = $height;
				$maxWidth = $width;
			}elseif($r < 1){
				$maxHeight = $height * $r;
				$maxWidth = $width * $r;
			}
			$temp_img = imagecreatetruecolor($maxWidth,$maxHeight); //创建画布
			$im = imagecreatefromjpeg($source_url);
			imagecopyresized($temp_img,$im,0,0,0,0,$maxWidth,$maxHeight,$width,$height);
			// imagecopyresampled($temp_img,$this->img,0,0,$_cut_width,$_cut_height,$new_width,$new_height,$this->width,$this->height);
			$isWrite = true;
		}
		$isWrite and ob_start();
		imagejpeg($temp_img);
		if($isWrite){
			$imgstr = ob_get_contents();
			$s->write($domain, $thumbFilePath, $imgstr);
			ob_end_flush();
		}
		imagedestroy($temp_img);
	}
	
	/**
	 * http://wmei-wmei5.stor.sinaapp.com/2014-11-20/2014112013491855079728.jpg
	 * @param unknown $url
	 * @return mixed
	 */
	private function getLocalPic($url) {
		return preg_replace("/http:\/\/[^\/]+/", C("UPLOAD_DOMAIN"), $url);
	}
	
}